
package logmatcher.executor;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;

import java.util.zip.Deflater;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


/**
 *  The class contains utility methods for packing up log files.
 *
 *  @version $Rev: 588 $
 */
public class LogSweeper {
	
    /** Class logger. */
    private static final Log LOGGER = LogFactory.getLog(LogSweeper.class);
    //~ Methods ----------------------------------------------------------------------------------------------

    /**
     *  Pack up source directory files into zip file.
     *
     *  @param sourceDir source directory.
     *  @param filter file selector.
     *  @param outputFileName output file.
     *  @param deleteFiles <code>true</code> if source files should be deleted after processing.
     *
     *  @throws FileNotFoundException if source directory does not exist.
     *  @throws IOException if any error occur while processing files.
     */
    public static void sweepToZip(
        String sourceDir, final String extension, String outputDir,String outputFileName, boolean deleteFiles)
        throws FileNotFoundException, IOException {
    	
    	LOGGER.debug("sweepToZip called");
    	
        File srcdir = new File(sourceDir);
        
        FilenameFilter filter = new FilenameFilter(){
            public boolean accept(File dir, String name) {
                return (name.endsWith(extension));
            }
        };        

        if (srcdir.exists()) {
            String[] filesToZip = srcdir.list(filter);

            if (filesToZip.length == 0) {
                return;
            }

            File dir = new File(outputDir);
            boolean res = dir.mkdirs();
            if(LOGGER.isDebugEnabled()){
                LOGGER.debug("directory "+outputDir+" creation: "+res);                    
            }
            String zipFileName = outputFileName.endsWith(".zip") ? outputFileName : (outputFileName + ".zip");           
            byte[] buffer = new byte[18024];

            if(LOGGER.isDebugEnabled()){
               LOGGER.debug("creating file: "+outputDir+File.separator+zipFileName);
            }
            ZipOutputStream out = new ZipOutputStream(new FileOutputStream(new File(outputDir+File.separator+zipFileName)));

            // Set the compression ratio
            out.setLevel(Deflater.DEFAULT_COMPRESSION);

            // iterate through the array of files, adding each to the zip file
            for (int i = 0; i < filesToZip.length; i++) {
                File fileToZip = new File(sourceDir, filesToZip[i]);

                // Associate a file input stream for the current file
                FileInputStream in = new FileInputStream(fileToZip);

                // Add ZIP entry to output stream.
                out.putNextEntry(new ZipEntry(filesToZip[i]));

                int len;

                while ((len = in.read(buffer)) > 0) {
                    out.write(buffer, 0, len);
                }

                // Close the current entry
                out.closeEntry();

                // Close the current file input stream
                in.close();

                if (deleteFiles) {
                    fileToZip.delete();
                }
            }

            // Close the ZipOutPutStream
            out.close();
        } else {
        	System.out.println(srcdir.getAbsoluteFile() + "does not exist");
        	System.out.println(srcdir.getAbsolutePath());
        	System.out.println(sourceDir);
            throw new FileNotFoundException("Unable to find source directory");
        }
    }
}
